﻿using System.Collections;
using System.Collections.Generic;
using LitJson;
using UnityEngine;
using UnityEngine.Networking;

public class WebRequestPost : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.S))
        {
            //使用litJson创建json格式的参数数据
            JsonData data = new JsonData();
            data["username"] = "chiry";
            data["age"] = 123;
            byte[] postBytes = System.Text.Encoding.Default.GetBytes(data.ToJson());

            //使用原生UnityWebRequest（推荐）
            StartCoroutine(UnityWebRequestPost("http://httpbin.org/post", postBytes));

            //使用UniRx
            //ObservableWWW.Post("你的url", postBytes, new Dictionary<string, string>() { { "Content-Type", "application/json" } })
            //.Subscribe(result => Debug.Log(result));
        }
    }

    IEnumerator UnityWebRequestPost(string url, byte[] postBytes)
    {
        UnityWebRequest request = new UnityWebRequest(url, "POST");

        request.uploadHandler = (UploadHandler) new UploadHandlerRaw(postBytes);
        request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
        request.SetRequestHeader("Content-Type", "application/json");
        yield return request.SendWebRequest();
        Debug.Log("Status Code: " + request.responseCode);
        if (request.isNetworkError || request.isHttpError)
        {
            Debug.LogError(request.error);
        }
        else
        {
            Debug.Log(request.downloadHandler.text);
        }
    }
}
